package com.hrms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hrms.dao.*;
import com.hrms.pojo.*;
import com.hrms.service.HiringRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hrms.service.SysUserService;
import com.hrms.utils.MdFive;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * <p>
 * 招聘记录表 服务实现类
 * </p>
 *
 * @author LK
 * @since 2021-10-19
 */
@Service
public class HiringRecordServiceImpl implements HiringRecordService {
    //注入mapper
    @Autowired(required = false)
    HiringRecordMapper hiringRecordMapper;
    @Autowired(required = false)
    EmpInformationMapper empInformationMapper;
    @Autowired(required = false)
    ApplyRecordMapper applyRecordMapper;
    @Autowired(required = false)
    SysUserService sysUserService;
    @Autowired(required = false)
    FileManageMapper fileManageMapper;
    @Autowired(required = false)
    SysUserMapper sysUserMapper;
    @Autowired(required = false)
    ContractManageMapper contractManageMapper;
    @Autowired(required = false)
    UserRoleRefMapper userRoleRefMapper;
    @Autowired(required = false)
    SysDeptMapper sysDeptMapper;
    //注入加密工具
    @Autowired(required = false)
    private MdFive mdFive;
    static String username = "user";

    @Override
    public HashMap<String, Object> select(HiringRecord h) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //定义分页对象
        Page<HiringRecord> page = new Page<>(h.getPage(), h.getRow());

        //条件构造器
        QueryWrapper<HiringRecord> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq(h.getId() != null, "id", h.getId());
        queryWrapper.like(h.getRecruitmentState() != null && !h.getRecruitmentState().equals(""), "recruitment_state", h.getRecruitmentState());

        //查询数据库
        Page<HiringRecord> aList = hiringRecordMapper.selectPage(page, queryWrapper);
        //当前页集合
        map.put("list", aList.getRecords());
        //总页数
        map.put("totalPage", aList.getPages());
        //总条数
        map.put("total", aList.getTotal());
        //当前页
        map.put("curPage", h.getPage());
        if (h.getPage() == 1) {
            //上一页
            map.put("prePage", 1);

        } else {
            map.put("prePage", h.getPage() - 1);

        }
        if (h.getPage() == aList.getPages()) {
            //下一页
            map.put("nextPage", aList.getPages());

        } else {
            map.put("nextPage", h.getPage() + 1);

        }
        //每页显示条数
        map.put("row", h.getRow());

        //查出所有部门名称
        List<SysDept> sysDepts = sysDeptMapper.selectList(null);
        map.put("sysDepts", sysDepts);

        return map;
    }

    @Override
    public HashMap<String, Object> add(HiringRecord h) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        int num = 0;
        if ("签约完成".equals(h.getRecruitmentState())) {
            //新建用户
            SysUser sysUser = new SysUser();
            //生成用户名
            int randomNum = new Random().nextInt(100);
            sysUser.setUserName(username + randomNum);
            //添加用户
            int staffId = getRandomNum();
            sysUser.setStaffId(staffId);
            //生成盐值
            String salt = UUID.randomUUID() + "";
            sysUser.setSalt(salt);
            //加密密码
            String md5Pass = mdFive.encrypt("123", salt);
            sysUser.setUserPwd(md5Pass);
            //新增
            sysUserMapper.insert(sysUser);
            //获取新的员工编号
            h.setEmpNum(String.valueOf(staffId));
            //创建员工基本信息
            EmpInformation emp = new EmpInformation();
            //添加员工基本信息
            ApplyRecord applyRecord = applyRecordMapper.selectAllById(h.getApplyContent());
            emp.setStaffId(sysUser.getStaffId());
            emp.setStaffName(applyRecord.getApplyName());
            emp.setStaffBirth(applyRecord.getApplyBirthday());
            emp.setStaffSex(applyRecord.getApplySex());
            emp.setStaffTel(applyRecord.getApplyTel());
            emp.setStaffEmail(applyRecord.getApplyEmail());
            emp.setStaffEducation(h.getFormalSchool());
            emp.setStaffDepartment(h.getDepartment());
            emp.setStaffPost(h.getPosition());
            emp.setStaffEntryTime(h.getWorkTime());
            emp.setStaffState(h.getState());
            //添加员工基本信息
            empInformationMapper.insert(emp);
            //创建员工档案
            FileManage fileManage = new FileManage();
            fileManage.setArchivesId(getRandomNum());
            fileManage.setStaffId(sysUser.getStaffId());
            //添加员工档案记录
            fileManageMapper.insert(fileManage);
            //创建员工合同
            ContractManage contractManage = new ContractManage();
            contractManage.setContractId(getRandomNum());
            contractManage.setStaffId(sysUser.getStaffId());
            contractManage.setStaffPost(h.getPosition());
            //添加员工合同
            contractManageMapper.insert(contractManage);
            //添加权限，默认是员工
            UserRoleRef roleRef = new UserRoleRef();
            if (h.getPosition().equals("管理员")) {
                roleRef.setUserId(sysUser.getUserId());
                roleRef.setRoleId(1);
            } else if (h.getPosition().equals("董事长")) {
                roleRef.setUserId(sysUser.getUserId());
                roleRef.setRoleId(2);
                userRoleRefMapper.insert(roleRef);
            } else if (h.getPosition().equals("部门经理")) {
                roleRef.setUserId(sysUser.getUserId());
                roleRef.setRoleId(3);
            } else {//普通员工权限
                roleRef.setUserId(sysUser.getUserId());
                roleRef.setRoleId(4);
            }

            //添加成功后，相应的部门人数减一
            List<SysDept> sysDepts = sysDeptMapper.selectList(null);
            for (SysDept dept : sysDepts) {
                if (h.getDepartment().equals(dept.getDeptName()) && dept.getDeptLack() != 0) {
                    sysDeptMapper.updateLess(h.getDepartment());
                }
            }
        }
        //新增
        num = hiringRecordMapper.insert(h);
        if (num > 0) {
            map.put("info", "保存成功");
        } else {
            map.put("info", "保存错误");
        }

        return map;
    }

    @Override
    public HashMap<String, Object> update(HiringRecord h) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        int num = 0;
        if ("签约完成".equals(h.getRecruitmentState())) {
            //新建用户
            SysUser sysUser = new SysUser();
            //生成用户名
            int randomNum = new Random().nextInt(100);
            sysUser.setUserName(username + randomNum);
            //添加用户
            int staffId = getRandomNum();
            sysUser.setStaffId(staffId);
            //生成盐值
            String salt = UUID.randomUUID() + "";
            sysUser.setSalt(salt);
            //加密密码
            String md5Pass = mdFive.encrypt("123", salt);
            sysUser.setUserPwd(md5Pass);
            //新增
            sysUserMapper.insert(sysUser);

            //获取新的员工编号
            h.setEmpNum(String.valueOf(staffId));
            //创建员工基本信息
            EmpInformation emp = new EmpInformation();
            //添加员工基本信息
            ApplyRecord applyRecord = applyRecordMapper.selectAllById(h.getApplyContent());
            emp.setStaffId(sysUser.getStaffId());
            emp.setStaffName(applyRecord.getApplyName());
            emp.setStaffBirth(applyRecord.getApplyBirthday());
            emp.setStaffSex(applyRecord.getApplySex());
            emp.setStaffTel(applyRecord.getApplyTel());
            emp.setStaffEmail(applyRecord.getApplyEmail());
            emp.setStaffEducation(h.getFormalSchool());
            emp.setStaffDepartment(h.getDepartment());
            emp.setStaffPost(h.getPosition());
            emp.setStaffEntryTime(h.getWorkTime());
            emp.setStaffState(h.getState());
            //添加员工基本信息
            empInformationMapper.insert(emp);
            //创建员工档案
            FileManage fileManage = new FileManage();
            fileManage.setArchivesId(getRandomNum());
            fileManage.setStaffId(sysUser.getStaffId());
            //添加员工档案记录
            fileManageMapper.insert(fileManage);
            //创建员工合同
            ContractManage contractManage = new ContractManage();
            contractManage.setContractId(getRandomNum());
            contractManage.setStaffId(sysUser.getStaffId());
            contractManage.setStaffPost(h.getPosition());
            //添加员工合同
            contractManageMapper.insert(contractManage);
            //添加权限
            UserRoleRef roleRef = new UserRoleRef();
            if (h.getPosition().equals("管理员")) {
                roleRef.setUserId(sysUser.getUserId());
                roleRef.setRoleId(1);
            } else if (h.getPosition().equals("董事长")) {
                roleRef.setUserId(sysUser.getUserId());
                roleRef.setRoleId(2);
                userRoleRefMapper.insert(roleRef);
            } else if (h.getPosition().equals("部门经理")) {
                roleRef.setUserId(sysUser.getUserId());
                roleRef.setRoleId(3);
            } else {//普通员工权限
                roleRef.setUserId(sysUser.getUserId());
                roleRef.setRoleId(4);
            }


            //添加成功后，相应的部门人数减一
            List<SysDept> sysDepts = sysDeptMapper.selectList(null);
            for (SysDept dept : sysDepts) {
                if (h.getDepartment().equals(dept.getDeptName()) && dept.getDeptLack() != 0) {
                    sysDeptMapper.updateLess(h.getDepartment());
                }
            }
        }
        //修改
        num = hiringRecordMapper.updateById(h);
        if (num > 0) {
            map.put("info", "保存成功");
        } else {
            map.put("info", "保存错误");
        }

        return map;
    }

    @Override
    public HashMap<String, Object> del(Integer i) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //删除
        int num = hiringRecordMapper.deleteById(i);
        if (num > 0) {
            map.put("info", "保存成功");
        } else {
            map.put("info", "保存错误");
        }
        return map;
    }

    //生成随机数
    private static int getRandomNum() {
        SecureRandom random = new SecureRandom();
        StringBuilder str = new StringBuilder();//定义可变字符串
        //随机生成数字，并添加到字符串
        for (int i = 0; i < 7; i++) {
            str.append(random.nextInt(10));
        }
        //将字符串转换为数字并输出
        return Integer.parseInt(str.toString());

    }
}
